package com.zeng.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * 通用工具方法
 */
@Slf4j
public class GenUtils {

    /**
     * 判断arr中是否包含str，忽略大小写
     */
    public static boolean stringArrayIgnoreCaseContains(String[] arr, String str) {
        for (String s : arr) {
            if(s.equalsIgnoreCase(str)) return true;
        }
        return false;
    }

    public static boolean stringIsNullOrWhiteSpace(String str) {
        return str == null || str.trim().isEmpty();
    }

    public static String AppLocation = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).getPath();

    private static List<Class<?>> allClasses;

    public static List<Class<?>> getAllClasses() {
        if (allClasses == null)
        {
            try{
                allClasses = getClassesByPackage("com");
            } catch (Exception ignored) {}
        }
        return allClasses;
    }

    public static List<Class<?>> getClassesByPackage(String packageName) throws NoSuchFieldException {
        File packageDir = new File(AppLocation,packageName);
        if(!packageDir.exists())
        {
            log.error("找不到对应的文件夹:{}", packageDir.getPath());
            return null;
        }
        List<Class<?>> classes = new ArrayList<>();

        fileRecursive(packageDir,file -> {
            String path = file.getPath();
            if(path.endsWith(".class")){
                String prePath = path.substring(0, path.lastIndexOf(packageName));
                String className = path.replace(prePath,"")
                        .replace(".class","")
                        .replace("/",".")
                        .replace("\\",".");

                try{
                    classes.add(Class.forName(className));

                } catch (ClassNotFoundException e){
                    log.error("加载类：<{}>失败，错误消息：{}",className,e.getMessage());
                }
            }
        },true);

        return classes;
    }



    /**
     * 对文件进行递归处理
     * @param baseDir 根目录
     * @param func 处理方式
     * @param isBack 是否由深如浅进行处理
     */
    public static void fileRecursive(File baseDir, Consumer<File> func, boolean isBack) {
        if(!isBack) func.accept(baseDir);

        File[] files = baseDir.listFiles();
        if(files != null) for (File file : files) fileRecursive(file, func, isBack);

        if(isBack) func.accept(baseDir);
    }






}
